<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="配置"
      width="50%"
      :close="handleClose"
      class="dialogStyle"
    >
      <el-button @click="addHandel" class="button_edit m-b20"> 添加 </el-button>
  
      <el-tree
        style="m-t20"
        :data="state.dataSource"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node d-flex">
            <div class="name">{{ data.stageName }}</div>
            <!-- <div class="time m-l20">
              {{ data.predictStartTime }} 至 {{ data.predictEndTime }}
            </div> -->
            <div class="department m-l20" v-if="data.responsibleDepartmentName">
              {{ data.responsibleDepartmentName }}
            </div>
            <div v-if="data.responsibleUserName" class="userName m-l20">
              {{ data.responsibleUserName }}
            </div>
            <span>
              <span
                class="projectPeople"
                style="margin-left: 8px"
                @click="update(node, data)"
              >
                编辑
              </span>
              <span class="projectPeople" @click="append(node, data)">
                添加下级
              </span>
              <span
                class="projectPeople"
                style="margin-left: 8px"
                @click="remove(node, data)"
              >
                删除
              </span>
              <!-- <span
                class="projectPeople"
                style="margin-left: 8px"
                @click="addPeople(node, data)"
              >
                添加责任人
              </span> -->
            </span>
          </span>
        </template>
      </el-tree>
  
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" class="button_cancel2">取消</el-button>
          <el-button @click="handleClose" class="button_view"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  
    <public-dialog
      :title="title"
      :width="'30%'"
      v-model:visible="visible"
      @onConfirm="onConfirm"
    >
      <div class="public-dialog-content d-flex j-center a-center">
        <el-form
          :model="dialogForm"
          ref="dialogFormRef"
          :rules="projectRules"
          class="demo-form-inline"
          label-width="100"
        >
          <el-form-item label="阶段名称" prop="">
            <el-input v-model="dialogForm.stageName" placeholder="" />
          </el-form-item>
          <el-form-item label="部门名称" prop="">
            <el-select
              v-model="dialogForm.responsibleDepartmentId"
              clearable
              placeholder=""
              @change="changeHandel(dialogForm.responsibleDepartmentId)"
            >
              <el-option
                v-for="item in state.allDepartmentList"
                :key="item.departmentId"
                :label="item.departmentName"
                :value="item.departmentId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="责任人名称" prop="">
            <el-select
              v-model="dialogForm.responsibleUserId"
              clearable
              placeholder=""
            >
              <el-option
                v-for="item in state.departmentPersonList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="阶段实施时间" prop="">
            <el-date-picker
              v-model="dialogForm.time"
              @change="handelChangeTime"
              :disabled="type == 1"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item> -->
        </el-form>
      </div>
    </public-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import PublicDialog from "@/components/PublicDialog.vue";
import {
	ElForm,
	ElSelect,
	ElFormItem,
	ElButton,
	ElTree,
	ElMessage,
} from "element-plus";
import { department, notificationApi } from "@/api/investment.js";

const props = defineProps({
	projectTypeId: {
		type: String,
		default: "",
	},
	projectId: {
		type: String,
		default: "",
	},
});
const title = ref("编辑");
const projectTypeId = ref("");

const dialogForm = ref({
	stageName: "",
	parentId: "",
	projectTypeId: "",
	level: "",
	responsibleDepartmentId: "",
	responsibleUserId: "",
	stageOrder: "",
	stageId: "",
});

const state = reactive({
	allDepartmentList: [],
	departmentPersonList: [],
	userByDepartmentList: [],
	dataSource: [],
});
// 新增
const addHandel = () => {
	title.value = "新增";
	visible.value = true;
	dialogForm.value = {
		level: 1,
		stageOrder: state.dataSource.length + 1,
		parentId: "",
		projectTypeId: projectTypeId.value,
		stageName: "",
		responsibleDepartmentId: "",
		responsibleUserId: "",
	};
};
const handelChangeTime = (e) => {
	console.log(e);
	if (e && e.length > 0) {
		dialogForm.value.predictStartTime = e[0];
		dialogForm.value.predictEndTime = e[1];
	}
};
const visible = ref(false);
//添加下级 tree按钮
const append = (node, data) => {
	title.value = "添加下级";
	dialogForm.value = {
		level: data.level + 1,
		stageOrder: node.parent.data.children
			? node.parent.data.children.length + 1
			: 1,
		parentId: data.stageId,
		projectTypeId: projectTypeId.value,
		stageName: "",
		responsibleDepartmentId: "",
		responsibleUserId: "",
	};
	visible.value = true;
	dialogForm.value.parentId = data.stageId;
};
//删除 tree按钮
const remove = (node, data) => {
	stageRemove({
		projectTypeId: projectTypeId.value,
		stageId: data.stageId,
	});
};
//编辑 tree按钮
const update = (node, data) => {
	title.value = "编辑";

	for (let key in data) {
		dialogForm.value[key] = data[key];
	}
	dialogForm.value.time = [
		dialogForm.value.predictStartTime,
		dialogForm.value.predictEndTime,
	];

	getLeaderByDepartmentId(data.responsibleDepartmentId);

	setTimeout(() => {
		visible.value = true;
	});
};

// 弹出层 提交
const onConfirm = () => {
	if (title.value == "添加下级") {
		stageCreate();
	} else if (title.value == "编辑") {
		stageUpdate();
	} else if (title.value == "新增") {
		stageCreate();
	}
};

/* 新增项目实施单个阶段 接口*/
const stageCreate = () => {
	notificationApi.stageCreate(dialogForm.value).then((res) => {
		if (res.code == 200) {
			dialogForm.value.stageId = res.data;
			dialogForm.value.responsibleDepartmentName = state.allDepartmentList.find(
				(item) => item.departmentId == dialogForm.value.responsibleDepartmentId
			)?.departmentName;
			dialogForm.value.responsibleUserName = state.departmentPersonList.find(
				(item) => item.userId == dialogForm.value.responsibleUserId
			)?.userName;
			if (title.value == "添加下级") {
				recursiveCallHandel(
					state.dataSource,
					dialogForm.value.parentId
				).children.push(dialogForm.value);
			} else {
				state.dataSource.push(dialogForm.value);
			}
			ElMessage.success("操作成功");
			visible.value = false;
		}
	});
};
/* 更新项目实施单个阶段 接口*/
const stageUpdate = () => {
	notificationApi.stageUpdate(dialogForm.value).then((res) => {
		if (res.code == 200) {
			ElMessage.success("操作成功");
			visible.value = false;
			getStage(projectTypeId.value);
		}
	});
};
/* 删除项目实施单个阶段 接口*/
const stageRemove = (param) => {
	notificationApi.stageRemove(param.stageId).then((res) => {
		if (res.code == 200) {
			recursiveCallHandel(state.dataSource, param.stageId, "删除");
			ElMessage.success("删除成功");
		}
	});
};

// 递归调用
const recursiveCallHandel = (data, id, type) => {
	let result;
	for (var i = 0; i < data.length; i++) {
		if (data[i].stageId == id) {
			if (type == "删除") {
				data.splice(i, 1);
				return;
			} else {
				if (!data[i].children) {
					data[i].children = [];
				}
				return data[i];
			}
		} else if (data[i].children && data[i].children.length > 0) {
			result = recursiveCallHandel(data[i].children, id, type);
			if (result) {
				return result;
			}
		}
	}
	return result;
};

// 获取所有部门
const getAllDepartments = () => {
	department.getAllDepartments().then((res) => {
		const { code, data, msg } = res;
		if (code == 200) {
			state.allDepartmentList = data;
		}
	});
};

// 获取项目 负责人
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
	department.getLeaderByDepartmentId(responsibleDepartmentId).then((res) => {
		const { code, data, msg } = res;
		if (code == 200) {
			state.departmentPersonList = data;
		}
	});
};

// 获取项目实施阶段配置
const getStage = (id) => {
	notificationApi.getStage(id).then((res) => {
		const { code, data, msg } = res;
		if (code == 200) {
			state.dataSource = data;
			dialogVisible.value = true;
		}
	});
};

const handleClose = () => {
	dialogVisible.value = false;
};

const changeHandel = (e) => {
	if (e) {
		dialogForm.value.responsibleUserId = "";
		getLeaderByDepartmentId(e);
	}
};

watch(
	() => visible.value,
	(value) => {
		if (!value) {
			dialogForm.value = {};
		}
	}
);
const dialogVisible = ref(false);

onMounted(() => {
	getAllDepartments();
	// getProjectPhase();
});

const open = (id) => {
	if (id) {
		getStage(id);
		projectTypeId.value = id;
	}
};
defineExpose({
	open,
});
</script>
<style lang="scss" scoped>
@import '@/views/constructionProjectManage/static/dialog.scss';
.projectPeople {
	color: #fff;
	cursor: pointer;

	text-align: center;
	font-size: 12px;
	// height: 20px;
	// line-height: 20px;
	margin-left: 10px;
	background-color: #d4ae85;
	border-radius: 10px;
	// padding-left: 5px;
	// padding-right: 5px;
  padding: 3px 5px;
}
.el-input,
.el-select,
.el-form-item {
	width: 100% !important;
}

.custom-tree-node {
	.name {
		min-width: 100px;
		height: 20px;
		background: #f7f7fa;
		border-radius: 6px;
		padding: 0 10px;
		text-align: center;
		font-size: 14px;
		color: #1a1a1a;
		line-height: 20px;
	}
	.time,
	.department,
	.userName {
		min-width: 104px;
		height: 20px;
		line-height: 20px;
		text-align: center;
		padding: 0 10px;
		font-size: 14px;
		color: #1a1a1a;
		border-radius: 6px;
		border: 1px solid #e3e7f1;
	}
}
:deep(.el-tree-node__content, .el-tree-node__children) {
	margin-bottom: 10px !important;
}
</style>
